package jp.sourceforge.akjrcp.flvtools.dropsomething;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import jp.sourceforge.akjrcp.akj_betas.Akj_betasPlugin;
import jp.sourceforge.akjrcp.akj_betas.Messages;
import jp.sourceforge.akjrcp.flvtools.basic.FFMpegPage;
import jp.sourceforge.akjrcp.flvtools.basic.FLVToolsPage;
import jp.sourceforge.akjrcp.util.FFMpegExecuter;
import jp.sourceforge.akjrcp.util.FFMpegUtils;
import jp.sourceforge.akjrcp.util.FLVTool2Executer;
import jp.sourceforge.akjrcp.util.FileNameUtils;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.DropTargetAdapter;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.part.ViewPart;

public class FLVConvertTab extends Composite {


	private Composite controler;

	private StackLayout stack;

	private FLVConvertTab self;



	private ProgressAndList plist;
	ViewPart view;

	private CCombo videoSize;

	private FFMpegExecuter executer;

	private CCombo audioRate;

	private CCombo videoRate;

	private CCombo videoBitRate;

	private CCombo audioBitRate;

	private CCombo audioChannel;

	private Button flowplayerHtml;

	private Button flowplayerSWF;
	
	private Button avisynth;

	private Button flvtool2;
	
	
	private boolean callFLVTool2;
	private boolean copyFlowPlayerSWF;
	private boolean copyFlowPlayerHTML;
	private void createLabel(Composite composite,String label){
		Label label1=new Label(composite,SWT.NULL);
		label1.setText(label);
	}
	public FLVConvertTab(ViewPart view,Composite parent, int style) {
		super(parent, style);
		this.view=view;
		self = this;
		stack = new StackLayout();
		this.setLayout(stack);

		controler = new Composite(this, SWT.NONE);
		controler.setLayout(new GridLayout(2, true));

		createLabel(controler,Messages.getString("flvconvert.video_size"));
		videoSize = new CCombo(controler, SWT.NULL);
		videoSize.add("320x240");
		videoSize.add("640x480");
		videoSize.select(0);
		// video rate
		createLabel(controler,Messages.getString("flvconvert.frame_rate"));
		videoRate = new CCombo(controler, SWT.NULL);
		videoRate.add("30");
		videoRate.add("29.7");
		videoRate.add("25");
		videoRate.add("15");
		videoRate.select(0);
		// video bitrate
		createLabel(controler,Messages.getString("flvconvert.video_bitrate"));
		videoBitRate = new CCombo(controler, SWT.NULL);
		videoBitRate.add("4000");
		videoBitRate.add("3000");
		videoBitRate.add("2000");
		videoBitRate.add("1500");
		videoBitRate.add("1000");
		videoBitRate.add("500");
		videoBitRate.select(2);
		// audio rate
		createLabel(controler,Messages.getString("flvconvert.audio_rate"));
		audioRate = new CCombo(controler, SWT.READ_ONLY);
		audioRate.add("44100");
		audioRate.add("22050");
		audioRate.add("11025");
		audioRate.select(0);
		// audio bitrate
		createLabel(controler,Messages.getString("flvconvert.audio_bitrate"));
		audioBitRate = new CCombo(controler, SWT.NULL);
		audioBitRate.add("196");
		audioBitRate.add("128");
		audioBitRate.add("96");
		audioBitRate.add("64");
		
		audioBitRate.select(1);
		// audio stereo
		createLabel(controler,Messages.getString("flvconvert.audio_channel"));
		audioChannel = new CCombo(controler, SWT.READ_ONLY);
		audioChannel.add("1");
		audioChannel.add("2");
		audioChannel.select(0);
		
		flowplayerHtml = new Button(controler,SWT.CHECK);
		flowplayerHtml.setText(Messages.getString("flvconvert.copy_html"));
		flowplayerHtml.setVisible(false);
		
		flowplayerSWF = new Button(controler,SWT.CHECK);
		flowplayerSWF.setText(Messages.getString("flvconvert.copy_swf"));
		flowplayerSWF.setVisible(false);
		avisynth = new Button(controler,SWT.CHECK);
		avisynth.setText(Messages.getString("flvconvert.use_avisynth"));
		avisynth.setSelection(true);
		avisynth.setToolTipText(Messages.getString("flvconvert.use_avisynth_tooltip"));
		
		flvtool2 = new Button(controler,SWT.CHECK);
		flvtool2.setText(Messages.getString("flvconvert.use_flvtool2"));
		flvtool2.setToolTipText(Messages.getString("flvconvert.use_flvtool2_tooltip"));
		flvtool2.setSelection(true);
		
		Transfer[] types = new Transfer[] { FileTransfer.getInstance() };

		int operations = DND.DROP_MOVE | DND.DROP_COPY;

		DropTarget target2 = new DropTarget(controler, operations);
		target2.setTransfer(types);

		target2.addDropListener(new DropMonitor());

		plist = new ProgressAndList(this,SWT.NONE);
		plist.getSimpleFileList().setInput(view);
		
		stack.topControl = controler;
	}
	
	public class ConvertFile implements Runnable{
		
		public void run(){
			boolean avsAvailable=FFMpegUtils.isAvisynthAvailable(new File(executer.getFfmpegPath()));
			
			while(true){
			int size=plist.getSimpleFileList().countFiles();
			if(size==0){
				view.getSite().getShell().getDisplay().asyncExec(new FinishConvert());
				break;
			}
			File file=plist.getSimpleFileList().getFileList()[0];
			String output=FileNameUtils.getChangedExtensionName(file,"flv");
			//exec ffmpeg;
			File tmp=null;
			boolean useAvisynth=avsAvailable && executer.isUseAvisynth() && FFMpegUtils.shouldUseAvisynth(file);
			if(useAvisynth){
			try {
				tmp=File.createTempFile("avs",".avs");
				FileWriter writer=new FileWriter(tmp);
				writer.write(FFMpegUtils.toAVSScript(file.getAbsolutePath()));
				writer.close();
				executer.setInput(tmp);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			}else{
				executer.setInput(file);
			}
			executer.setOutput(new File(output));
		
			
			try {
				
				executer.execute();
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(useAvisynth){
				boolean result=tmp.delete();
				if(!result){
					DropsomethingView.log.warn("tmp not deleted:"+tmp);
				}
			}
			
			if(callFLVTool2){
				
				String path = Akj_betasPlugin.getDefault().getPreferenceStore()
				.getString(FLVToolsPage.FLVTOOL2_PATH);
				DropsomethingView.log.info(path);
				if(path.endsWith("flvtool2.exe")){
				FLVTool2Executer flvtool2Executer=new FLVTool2Executer(path,Akj_betasPlugin.getDefault().getProcessPrinter());
				flvtool2Executer.setInput(new File(output));
				try {
					flvtool2Executer.execute();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				}
			}
			
			//change next.
			//change xxx.
			plist.getSimpleFileList().popFile();
			
			view.getSite().getShell().getDisplay().asyncExec(new UpdateTable());
			}
		}
	}
	
	/*
	public class SettingMonitor implements IPropertyChangeListener{

		public void propertyChange(PropertyChangeEvent event) {
			
			if(event.getProperty().equals(FFMpegPage.FFMPEG_PATH)){
				String ffmpegPath=Akj_betasPlugin.getDefault().getPreferenceStore().getString(FFMpegPage.FFMPEG_PATH);
				
				if(!FFMpegUtils.isAvailable(ffmpegPath)){
				self.setEnabled(true);
				}else{
				self.setEnabled(false);
				}
			}
		}
		
	}*/
	
	public class FinishConvert implements Runnable{
		public void run(){
			stack.topControl = controler;
			layout();
		}
	}
	
	
	public class UpdateTable implements Runnable{
		public void run(){
			
			plist.getSimpleFileList().refresh(true);
			plist.getSimpleFileList().getTable().select(0);
		}
	}
	
	
	public void startConvert(){
		String ffmpegPath=Akj_betasPlugin.getDefault().getPreferenceStore().getString(FFMpegPage.FFMPEG_PATH);
		
		if(!FFMpegUtils.isFFMpegAvailable(ffmpegPath)){
			return;
		}
		
		plist.getSimpleFileList().getTable().select(0);
		
		executer = new FFMpegExecuter(ffmpegPath,Akj_betasPlugin.getDefault().getProcessPrinter());
		
		executer.setVideoBitrate(Integer.parseInt(videoBitRate.getText()));
		executer.setVideoRate(Double.parseDouble(videoRate.getText()));
		executer.setVideoSize(videoSize.getText());
		executer.setAudioChannel(Integer.parseInt(audioChannel.getText()));
		executer.setAudioBitrate(Integer.parseInt(audioBitRate.getText()));
		executer.setAudioSampleRate(Integer.parseInt(audioRate.getText()));
		
		executer.setUseAvisynth(avisynth.getSelection());
		
		callFLVTool2=flvtool2.getSelection();
		copyFlowPlayerHTML=flowplayerHtml.getSelection();
		copyFlowPlayerSWF=flowplayerSWF.getSelection();
		
		
		Thread t=new Thread(new ConvertFile());
		t.start();
	}
	public void addDragAndDropFile(String path){
		if(stack.topControl==controler){
			stack.topControl=plist;
			plist.addFile(path);
			
			layout();
			
			
			//little bit worry
			startConvert();
			
		}else{
			plist.addFile(path);
			layout();
		}
		
	}
	
	public class DropMonitor extends DropTargetAdapter{
		public void dragEnter(DropTargetEvent event){
			//System.out.println("drag enter:"+event.data);
		}
		public void dragOver(DropTargetEvent event){
			//System.out.println("drag over:"+event.data);
			}
		public void drop(DropTargetEvent event){
			//System.out.println("drop:"+event.data);
			
			//System.out.println(event.data.getClass().getName());
			String files[]=(String[])event.data;
		
		
			for(int i=0;i<files.length;i++){
				addDragAndDropFile(files[i]);
			}
			
			}
	}

}
